package com.eastcom.notice;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import org.apache.log4j.Logger;

public class NoticeMessage
{
  private Logger log;
  private boolean isConnect = true;
  private Socket socket;
  private OutputStream outStream;
  private InputStream inSteam;
  private ObjectOutputStream objOut;
  private List<NoticeMessage> aliveSocket;

  NoticeMessage(Socket socket, List<NoticeMessage> aliveSocket)
  {
    this.socket = socket;
    this.aliveSocket = aliveSocket;
    try
    {
      this.outStream = socket.getOutputStream();
      this.objOut = new ObjectOutputStream(this.outStream);
      this.inSteam = socket.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
      this.isConnect = false;
    }

    new Thread(new Runnable()
    {
      public void run() {
        try {
          if (NoticeMessage.this.inSteam.read() == -1);
          NoticeMessage.this.isConnect = false;
        }
        catch (IOException e)
        {
          NoticeMessage.this.aliveSocket.remove(NoticeMessage.this);
          NoticeMessage.this.log.debug("the Notice[Socket] client is Close: " + NoticeMessage.this.socket);
          NoticeMessage.this.isConnect = false;
          e.printStackTrace();
        }
      }
    }).start(); }

  public boolean isConnect() {
    return this.isConnect;
  }

  public void sendMessage(String xml)
  {
    if (!(this.isConnect)) return;
    try {
      this.log.debug("send message: " + this.socket + " : " + xml);
      this.objOut.writeObject(xml);
      this.objOut.flush();
    } catch (IOException e) {
      e.printStackTrace();
      this.isConnect = false;
    }
  }
}